package service

import (
	"fmt"
	"github.com/PhlexTheCharr/gofurry-cloud-service/apps/openlist/util/dao"
	"github.com/PhlexTheCharr/gofurry-cloud-service/apps/openlist/util/models"
	"github.com/PhlexTheCharr/gofurry-cloud-service/common"
	"github.com/PhlexTheCharr/gofurry-cloud-service/roof/env"
	"github.com/gofiber/fiber/v2"
	"math/rand"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// Logo 支持的图片格式
var validExts = env.GetServerConfig().Openlist.ImageExts

type utilService struct{}

var utilSingleton = new(utilService)

func GetUtilService() *utilService { return utilSingleton }

// 获取 Logo 图片
func (svc *utilService) GetLogoService() (string, common.GFError) {
	logoPath := env.GetServerConfig().Openlist.LogoPath

	// 读取文件
	files, err := os.ReadDir(logoPath)
	if err != nil {
		return "", common.NewServiceError(fmt.Sprintf("读取Logo目录失败: %v", err))
	}

	var logoFile string
	for _, file := range files {
		if !file.IsDir() && isValidImage(file.Name()) {
			logoFile = file.Name()
			break
		}
	}

	if logoFile == "" {
		return "", common.NewServiceError("未找到Logo图片")
	}

	// 返回图片路径
	return filepath.Join(logoPath, logoFile), nil
}

// GetImageService 随机获取一张背景图片
func (svc *utilService) GetImageService(c *fiber.Ctx) (string, common.GFError) {
	// 禁止浏览器/代理缓存
	c.Set("Cache-Control", "no-cache, no-store, must-revalidate")
	c.Set("Pragma", "no-cache")
	c.Set("Expires", "0")

	imagePath := env.GetServerConfig().Openlist.ImagePath

	var imageFiles []string
	err := filepath.Walk(imagePath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if !info.IsDir() && isValidImage(info.Name()) {
			imageFiles = append(imageFiles, path)
		}
		return nil
	})

	if err != nil {
		return "", common.NewServiceError(fmt.Sprintf("读取图片目录失败: %v", err))
	}

	if len(imageFiles) == 0 {
		return "", common.NewServiceError("未找到任何图片")
	}

	rand.Seed(time.Now().UnixNano())
	randomIndex := rand.Intn(len(imageFiles))

	return imageFiles[randomIndex], nil
}

// 返回随机金句
func (svc *utilService) GetSayingService() (string, common.GFError) {
	// 查总条数并生成一个随机值
	count, gfError := dao.GetUtilDao().Count(models.OlSaying{})
	if gfError != nil {
		return "", gfError
	}
	rand.Seed(time.Now().UnixNano())
	randomIndex := rand.Intn(int(count))
	record, err := dao.GetUtilDao().GetSayingByOrder(randomIndex)
	if err != nil || record == nil {
		return "", common.NewServiceError(fmt.Sprintf("查询金句记录失败: %v", err))
	}
	text := fmt.Sprintf(`(function gofurrySaying(){var gofurrySaying="%s";var dom=document.querySelector('#gofurrySaying');Array.isArray(dom)?dom[0].innerText=gofurrySaying:dom.innerText=gofurrySaying;})()`, record.Saying)
	return text, nil
}

// 检查文件是否为有效的图片格式
func isValidImage(filename string) bool {
	ext := filepath.Ext(filename)
	for _, validExt := range strings.Split(validExts, ",") {
		if strings.EqualFold(ext, validExt) {
			return true
		}
	}
	return false
}
